<template>
    <div>
        <div class="outmain ba_f instoreorderdl">
            <div class="shuju_title mar_b20">
                <div class="shuju_title_text">
                    <span>堂食订单详情</span>
                </div>
            </div>
            <div class="flex-bet flex-y-top">
                <el-form :inline="true" :model="formInline" class="demo-form-inline searchform">
                    <div>
                        <el-form-item label="订单号" class="mar_l20">
                            <el-input v-model="formInline.keyword" size="medium" placeholder="请输入订单号"
                                      @input="onSearch"></el-input>
                        </el-form-item>
                        <el-form-item label="下单时间" class="mar_l20">
                            <el-radio-group v-model="formInline.tabPosition" class="mar_r20">
                                <el-radio-button label="1">今天</el-radio-button>
                                <el-radio-button label="2">昨天</el-radio-button>
                                <el-radio-button label="3">一周</el-radio-button>
                                <el-radio-button label="0">全部</el-radio-button>
                            </el-radio-group>
                            <el-date-picker
                                    v-model="formInline.timeData"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item class="mar_l20">
                            <el-button type="primary" @click="onSearch" size="medium">搜索</el-button>
                            <el-button size="medium" @click="getCode">查看餐桌码</el-button>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div class="flex-bet flex-y-top mar_t20">
                <div class="bflex-7">
                    <el-tabs v-model="activeName" class="mar_b20" @tab-click="handleTabClick">
                      <el-tab-pane label="待完成" name="1"></el-tab-pane>
                      <el-tab-pane label="全部订单" name="0"></el-tab-pane>
                    </el-tabs>
                    <div v-if="orderListData && orderListData.length>0">
                        <div class="orderList pad_20 flex-bet curs"
                             v-for="(item,index) in orderListData" :key="index"
                             :class="{'orderListHover':orderListHover==index}"
                             @click="clickOrderList(item,index)">
                            <div class="flex-g-0 number">桌台{{item.number}}</div>
                            <div class="flex-g-1 wei fon_12 color_3 mar_l10">
                            <div class="flex-bet">
                              <div>开台时间：<span v-if="item.createdAt">{{getYMDHMS(item.createdAt)}}</span></div>
                              <div class="" v-if="item.receiptAt && item.state=='2'">
                                就餐时间：{{timeStamp(Math.round(new
                              Date().getTime()/1000).toString()-item.receiptAt)}}
                              </div>
                              <div class="" v-if="item.completeAt && item.state=='3'">
                                就餐时间：{{timeStamp(item.completeAt-item.receiptAt)}}
                              </div>
                            </div>
                            <div class="flex-bet">
                              <div>就餐人数：{{item.people}}人</div>
                              <div class=""></div>
                            </div>
                            <div class="flex-bet">
                              <div>实付金额：{{item.money}}
                                <span class="mar_l5 color-red" v-if="item.state=='1' || (item.state=='4') || (item.eatType=='2' && item.state=='2')">(未支付)</span>
                                <span class="mar_l5 color-green" v-if="(item.state=='2' || item.state=='3') && item.eatType=='1'">(已支付)</span>
                                <span class="mar_l5 color-green" v-if="item.state=='3' && item.eatType=='2'">(已支付)</span>
                                <span class="mar_l5 color-red" v-if="item.state=='5'">(已退款)</span>
                              </div>
                              <div class="type daifukuan" v-if="item.state=='1' && item.eatType=='1'">待付款</div>
                              <div class="type daifukuan" v-if="item.state=='1' && item.eatType=='2'">待接单</div>
                              <!--                                    <div class="type" v-if="item.state=='2' && item.eatType=='2'">已接单</div>-->
                              <div class="type2 ddBg1" v-if="(item.state=='2' && item.eatType=='1') || (item.state=='2' && item.eatType=='2')">就餐中</div>
                              <div class="type2 ddBg2" v-if="(item.state=='3' && item.eatType=='1') || (item.state=='3' && item.eatType=='2')">已完成</div>
                              <div class="type yiquxiao" v-if="item.state=='4'">已取消</div>
                              <div class="type2 bg3" v-if="item.state=='5'">已退款</div>
                            </div>
                          </div>
                        </div>
                        <el-pagination
                                background
                                layout="prev, pager, next"
                                :total="page.total"
                                :page-size="page.size"
                                :current-page.sync='page.currentPage'
                                :hide-on-single-page="page.value"
                                @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                    <div v-show="orderListData.length==0" class="zwsj flex-center">
                        <div class="t_c">
                            <div><img src="../../../assets/img/order/quxiaodan.png" style="width: 180px;height: 180px;"/>
                            </div>
                            <div class="mar_t10">暂无订单</div>
                        </div>
                    </div>
                </div>
                <div class="bflex-3 orderMsg pad_20" v-if="orderListData && orderListData.length>0">
                <div v-for="(ditem,dindex) in orderListData[orderListHover].detail" :key="dindex">
                  <div class="msgNumber">桌台：{{ditem.number}}</div>
                  <div class="shuju_title">
                    <div class="shuju_title_text">
                      <span>顾客信息</span>
                    </div>
                  </div>
                  <div class="bor_b_de4 pad_b_10 fon_12 lh25 color_6">
                    <div class="flex">
                      <div class="bflex-5"><span class="wei">用户昵称</span>：
                        <span v-if="ditem.origin!='5'">{{ ditem.userName }}(uid:{{ ditem.userId }})</span>
                        <span v-else>无</span>
                      </div>
                      <div class="bflex-5"><span class="wei">手机号：</span>
                        <span v-if="ditem.origin!='5'">{{ ditem.userTel }}</span>
                        <span v-else>无</span>
                      </div>
                    </div>
                  </div>
                  <div class="shuju_title">
                    <div class="shuju_title_text">
                      <span class="wei">订单信息</span>
                    </div>
                  </div>
                  <div class="bor_b_de4 pad_b_10 fon_12 lh25 color_6">
                    <div class="flex">
                      <div class="bflex-5"><span class="wei">订单来源：</span>
                        <span v-if="ditem.origin=='1'">微信小程序</span>
                        <span v-if="ditem.origin=='2'">微信公众号</span>
                        <span v-if="ditem.origin=='3'">支付宝小程序</span>
                        <span v-if="ditem.origin=='4'">百度小程序</span>
                        <span v-if="ditem.origin=='5'">收银台下单</span>
                      </div>
                      <!--                                <div class="bflex-5"><span class="wei">桌台信息：</span>{{ ditem.tableName }}</div>-->
                    </div>
                    <div class="flex">
                      <div class="bflex-5"><span class="wei">就餐模式：</span>
                        <span v-if="ditem.eatType=='1'">先结账后用餐</span>
                        <span v-if="ditem.eatType=='2'">先用餐后结账</span>
                      </div>
                      <div class="bflex-5"><span class="wei">订单号：</span>{{ditem.outTradeNo}}</div>
                    </div>
                    <div class="flex">
                      <div class="bflex-5"><span class="wei">订单金额：</span>{{(+ditem.money)+(+ditem.allPreferential)}}<span v-if="ditem.vipDiscount>0">（会员优惠：{{ditem.vipDiscount}}）</span>
                      </div>
                      <div class="bflex-5"><span class="wei">桌位费：</span>
                        <span>{{ditem.tablewareMoney}}</span>
                      </div>
                    </div>
                    <div class="flex">
                      <div class="bflex-5"><span class="wei">订单优惠：</span>{{ditem.allPreferential}}</div>
                      <div class="bflex-5"><span class="wei">实付金额：</span><span class="color_rb wei">{{ditem.money}}</span></div>
                    </div>
                    <div class="flex">
                      <div class="bflex-5"><span class="wei">支付状态：</span>
                        <span class="color_rb wei" v-if="(ditem.state=='1' || ditem.state=='2') && ditem.eatType=='2'">待付款</span>
                        <span class="color_rb wei" v-if="ditem.state=='1' && ditem.eatType=='1'">待付款</span>
                        <span class="color-green wei" v-if="(ditem.state=='2' || ditem.state=='3') && ditem.eatType=='1'">已支付</span>
                        <span class="color-green wei" v-if="ditem.state=='3' && ditem.eatType=='2'">已支付</span>
                        <span class="color-red wei" v-if="ditem.state=='5'">已退款 ({{ditem.refundMoney}})</span>
                        <span class="color_rb wei" v-if="ditem.state=='4'">已取消</span>
                      </div>
                      <div class="bflex-5"><span class="wei">支付方式：</span>
                        <template v-if="ditem.payAt && ditem.payAt!=='0'">
                          <span v-if="ditem.payMode=='1'">微信支付</span>
                          <span v-if="ditem.payMode=='2'">支付宝支付</span>
                          <span v-if="ditem.payMode=='3'">百度支付</span>
                          <span v-if="ditem.payMode=='4'">公众号支付</span>
                          <span v-if="ditem.payMode=='5'">余额支付</span>
                          <span v-if="ditem.payMode=='6'">线下支付（现金支付）</span>
                          <span v-if="ditem.payMode=='7'">线下支付（pos机支付）</span>
                          <span v-if="ditem.payMode=='8'">线下支付（自有微信支付）</span>
                          <span v-if="ditem.payMode=='9'">线下支付（自有支付宝支付）</span>
                        </template>
                      </div>
                    </div>
                  </div>
                  <div class="goodsList">
                    <el-table
                        :data="orderListData[orderListHover].goodsArr"
                        stripe
                        height="250">
                      <el-table-column
                          label="商品"
                          prop="name"
                          width="300"
                      >
                        <template slot-scope="scope">
                          <div class="flex wei">{{scope.row.name}}
                            <span class="color-green mar_l5" v-if="scope.row.addType=='1'">加{{scope.row.addNum}}</span>
                          </div>
                          <div v-show="scope.row.data">规格：{{scope.row.data}}</div>
                          <div v-show="scope.row.attribute">属性：{{scope.row.attribute}}</div>
                          <div v-show="scope.row.material">加料：{{scope.row.material}}</div>
                        </template>
                      </el-table-column>
                      <el-table-column
                          prop="num"
                          label="单价*数量"
                      >
                        <template slot-scope="scope">
                          <div>{{scope.row.money}} * {{scope.row.num}}</div>
                        </template>
                      </el-table-column>
                      <el-table-column
                          prop="sumMoney"
                          label="金额"
                      >
                      </el-table-column>
                    </el-table>
                    <div class="flex flex-col-end fon_14 mar_r10 mar_t5">
                      <div>桌位费：{{ditem.tablewareMoney}}元</div>
                    </div>
                  </div>
                  <div class="pad_10 t_c anniu">
                    <el-button plain size="medium" v-if="ditem.state!='1'"
                               @click="modifyFastOrder(ditem.id,'print')">打印小票
                    </el-button>
                    <el-button type="primary" size="medium" class="jiedan"
                               v-if="ditem.state=='1' && ditem.eatType=='2'"
                               @click="modifyFastOrder(ditem.id,'receipt')">接单并打印
                    </el-button>
                    <el-button type="success" size="medium" class="jiezhang" v-if="ditem.state=='2'"
                               @click="modifyFastOrder(ditem.id,'checkOut')">
                      <span v-if="ditem.eatType=='1'">完成并清台</span>
                      <span v-if="ditem.eatType=='2'">结账并清台</span>
                    </el-button>
                    <el-button plain size="medium" type="danger" v-if="ditem.state=='1'"
                               @click="modifyFastOrder(ditem.id,'close')">关闭订单并清台
                    </el-button>
                    <el-button plain size="medium" type="danger" v-if="ditem.state=='2' && ditem.eatType=='1'  && (ditem.origin!='5' && ditem.payMode!='6' && ditem.payMode!='7' && ditem.payMode!='8' && ditem.payMode!='9')"
                               @click="modifyFastOrder(ditem.id,'refund',ditem)">退款并清台
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
        </div>
        <el-dialog title="退款" :visible.sync="dialogTableVisible4" :close-on-click-modal='false' width="500px"
                   class="tishidialog">
            <div class="t_c">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="退款类型">
                        <div class="t_l">
                            <el-radio-group v-model="form.type">
                                <el-radio label="1">全额退款</el-radio>
                                <el-radio label="2">自定义退款</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                    <el-form-item label="退款金额" v-show="form.type!='1'">
                        <el-input v-model="form.money" placeholder="请输入退款金额"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="medium" @click="dialogTableVisible4=false">取 消</el-button>
                <el-button size="medium" type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog
                title="查看小程序码"
                :visible.sync="dialogFormVisible"
                width="600px"
                :close-on-click-modal="false"
        >
            <div class="t_c">
                <div>
                    <img :src="codeimg" style="width: 200px;height: 200px;">
                </div>
                <a :href='downloadCode(codeimg)' :title="'Id：'+tableId">
                    <el-button size="medium" type="primary" class="mar_t20">下载二维码图片</el-button>
                </a>
            </div>
            <!--            <div slot="footer" class="dialog-footer">-->
            <!--                <el-button size="medium" @click="close">取 消</el-button>-->
            <!--                <el-button size="medium" type="primary" @click="save">确 定</el-button>-->
            <!--            </div>-->
        </el-dialog>
      <div style="height: 0; overflow: hidden">
        <TsPrint :data="printData" ref="tsprint" />
      </div>
    </div>
</template>
<script>
    import {inStoreOrderList, modifyInStoreOrder} from "@/api/instore";
    import {getStoreConfig,getCode} from "@/api/setup";
    import {changeDate} from "@/utils/index";
    import index from '../../../api/index';
    import {orderContent} from '@/api/order';
    import TsPrint from "@/components/printTem/tsPrint";
    import {mapState} from "vuex";

    export default {
        components: {TsPrint},
        created() {
            if (this.$route.query.tableId) {
                this.tableId = this.$route.query.tableId
            }
            if (this.$route.query.activeName) {
                this.activeName = this.$route.query.activeName
            }
            this.init();
            this.fetchData();
        },
        computed: {
            ...mapState(['storeId']),
        },
        data() {
            return {
                activeName: '1',
                formInline: {
                    tabPosition: '1',
                    keyword: '',
                    userChannel: '',
                    timeData: ''
                },
                form: {
                    type: '1',
                    money: '',
                    orderId:'',
                },
                payMode: '',
                list: [],
                orderListHover: 0,
                orderListData: [],
                listLoading: false,
                selectRows: "",
                elementLoadingText: "正在加载...",
                page: {
                    total: 0,
                    size: 10,
                    currentPage: 1,
                },
                dialogTableVisible4: false,
                dialogFormVisible: false,
                codeimg:'',
              printData: {},
            }
        },
        methods: {
            async init() {
                const {data} = await getStoreConfig({ident: 'instoreSet',storeId:this.storeId});
                this.payMode = data.payMode ? data.payMode : '1'
            },
            async fetchData() {
                var params = {
                    tableId: this.tableId,
                    page: this.page.currentPage,
                    timeType: this.formInline.tabPosition,
                    keyword: this.formInline.keyword,
                    state: this.activeName,
                    startTime: this.formInline.timeData[0] ? changeDate(this.formInline.timeData[0]) : '',
                    endTime: this.formInline.timeData[1] ? changeDate(this.formInline.timeData[1]) : '',
                    storeId:this.storeId
                }
                const {data, count} = await inStoreOrderList(params);
                this.orderListData = data ? data : [];
                this.page.total = count;
            },
            handleTabClick() {
                this.orderListHover = 0
                this.page.currentPage = 1
                this.fetchData()
            },
            handleCurrentChange(val) {
                this.orderListHover = 0
                this.page.currentPage = val;
                this.fetchData()
            },
            clickOrderList(item, index) {
                this.orderListHover = index
            },
            onSearch() {
                this.fetchData()
            },
            async getCode() {
                if(this.tableId){
                    this.dialogFormVisible = true
                    const {data} = await getCode({tableId:this.tableId,page:'yb_wm/shop/in/goods',ident:'table',storeId:this.storeId});
                    this.codeimg = data?data:''
                }else {
                    this.$baseMessage('暂无桌子id', "success");
                }
            },
            downloadCode(row){
                let backendPath = index.backendPath
                return backendPath + "channel/in-store/download-code?url="+row
            },
            async modifyFastOrder(orderId, type,ditem) {
                if (type == 'receipt') {
                    const {msg} = await modifyInStoreOrder({orderId, type,});
                    this.$baseMessage(msg, "success");
                    const { data } = await orderContent({orderId,orderType:2});
                    Object.keys(data).map(key=>{
                      this.printData = data[key];
                      this.$nextTick(() => {
                        this.$refs.tsprint.printElement(key);
                      });
                    })
                    this.fetchData()
                } else if (type == 'close') {
                    this.$baseConfirm("您确定关闭订单并清台吗", null, async () => {
                        const {msg} = await modifyInStoreOrder({orderId, type,});
                        this.$baseMessage(msg, "success");
                        this.fetchData()
                    });
                } else if (type == 'checkOut') {
                    this.$baseConfirm("您确定结账此订单吗", null, async () => {
                        const {msg} = await modifyInStoreOrder({orderId, type,});
                        this.$baseMessage(msg, "success");
                        this.fetchData()
                    });
                } else if (type == 'refund') {
                    this.$baseConfirm("您确定退款此订单吗", null, async () => {
                        this.dialogTableVisible4 = true
                        this.form.money = ditem.money
                        this.form.orderId = orderId
                    });
                } else if (type == 'print') {
                    const {msg} = await modifyInStoreOrder({orderId, type,});
                    this.$baseMessage(msg, "success");
                    const { data } = await orderContent({orderId,orderType:2});
                    Object.keys(data).map(key=>{
                      this.printData = data[key];
                      this.$nextTick(() => {
                        this.$refs.tsprint.printElement(key);
                      });
                    })
                    this.fetchData()
                } else {
                    this.$baseMessage('敬请期待', "success");
                    this.fetchData()
                }
            },
            async save(){
                const {msg} = await modifyInStoreOrder({orderId:this.form.orderId, type:'refund',money:this.form.money,storeId:this.storeId});
                this.$baseMessage(msg, "success");
                this.dialogTableVisible4 =false
                this.fetchData()
            },
            getYMDHMS(timestamp) {
                let time = new Date(timestamp * 1000)
                let year = time.getFullYear()
                let month = time.getMonth() + 1
                let date = time.getDate()
                let hours = time.getHours()
                let minute = time.getMinutes()
                let second = time.getSeconds()
                if (month < 10) {
                    month = '0' + month
                }
                if (date < 10) {
                    date = '0' + date
                }
                if (hours < 10) {
                    hours = '0' + hours
                }
                if (minute < 10) {
                    minute = '0' + minute
                }
                if (second < 10) {
                    second = '0' + second
                }
                return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
            },

            timeStamp(second_time) {
                var time = parseInt(second_time) + "秒";
                if (parseInt(second_time) > 60) {
                    var second = parseInt(second_time) % 60;
                    var min = parseInt(second_time / 60);
                    time = min + "分" + second + "秒";
                    if (min > 60) {
                        min = parseInt(second_time / 60) % 60;
                        var hour = parseInt(parseInt(second_time / 60) / 60);
                        time = hour + "小时" + min + "分" + second + "秒";
                        if (hour > 24) {
                            hour = parseInt(parseInt(second_time / 60) / 60) % 24;
                            var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
                            time = day + "天" + hour + "小时" + min + "分" + second + "秒";
                        }
                    }
                }
                return time;
            },
        },
    }
</script>
<style lang="scss">
    .instoreorderdl {
      .orderList {
        border-bottom: 1px solid #EBEEF5;
        background: #fff;

        .number {
          background: #4675e0;
          padding: 18px 12px;
          color: #fff;
          font-weight: bold;
          border-radius: 5px;
        }

        .type {
          background: #54BBA5;
          color: #fff;
          padding: 2px;
          border-radius: 3px;
        }
        .type2 {
          color: #fff;
          padding: 2px;
          border-radius: 3px;
        }

        .daifukuan {
          background: #f00;
        }

        .yiwanc {
          background: #67C23A;
        }

        .yiquxiao {
          background: #c3c3c3;
        }
      }

      .orderListHover, .orderList:hover {
        background: #f7f7f7;
      }

      .orderList:hover {
        background: #f7f7f7;
      }

      .orderMsg {
        min-height: 500px;
        border-left: 1px solid #E1E1E1;

        .shuju_title {
          background: #fff;
        }

        .msgNumber {
          color: #155BD4;
          font-size: 20px;
          font-weight: bold;
        }

        .goodsList {
          width: 510px;
          .el-table__header-wrapper {
            font-size: 12px;
          }

          .el-table__body-wrapper {
            font-size: 12px;
          }

          .goodTit {
            background: #f5f5f5;
          }
        }

        .anniu {
          .jiedan, .jiezhang {
            width: 160px;
          }

          .el-button--danger.is-plain:hover {
            border-color: #fbc4c4;
            color: #fff;
          }
        }
      }
    }
    .ddBg1{
      background: #FEB101;
    }
    .ddBg2{
      background: #adadad;
    }
    .bg3{
      background: #F56C6C;
    }
    /*.instoreorderdl .orderMsg .anniu .el-button--danger.is-plain:hover {*/
    /*    border-color: #fbc4c4;*/
    /*    color: #fff;*/
    /*}*/
</style>
